<?php
/**
 * Run of the mill mailinkje
 */
$mailing = "
Geachte #aanhef# #user.lastname#,

U heeft het volgende besteld:
#product[0]#
#product[1]#
#product[2]#
#product[]#

Voor de prijs van &euro; #prijs#

#naam met spaties en een hekje#

#user.notavailable#

Groeten #unused#

Sales";

/**
 * Define vars en pomp ze in een array (object, array en scalars)
 */
$user->lastname = "Lous";
$aanhef = "heer";
$product = array("Zend voucher", "Zend Server Licence");
$prijs = number_format(2123.504, 2, ',', '.');

$vars = array();
$vars['user'] = $user;
$vars['aanhef'] = $aanhef;
$vars['product'] = $product;
$vars['prijs'] = $prijs;


// define regexp (check this out!) let op de e modifier
$regexp = "`#([\w_]+?)(\.([\w_]+)|\[([\w_]*)\])?#`se";

// leuk puzzlewerk
$replacement = 'array_key_exists("\\1", $vars)?
					(
					is_scalar($vars["\\1"])?
						($vars["\\1"]):
						(
						is_array($vars["\\1"])?
							(
							strlen(trim("\\4"))>0&&array_key_exists("\\4",$vars["\\1"])?								
								$vars["\\1"]["\\4"]:null							
							)
							:
							(
							is_object($vars["\\1"])?
								(
								strlen(trim("\\3"))>0&&isset($vars["\\1"]->{"\\3"})?								
									$vars["\\1"]->{"\\3"}:null							
								)
								:(null)
							)
						)
					)
					:(null)';
					

echo '<pre>';
//print_r($vars);

$txt = preg_replace($regexp, $replacement, $mailing);

echo $txt;

/* 

$vars = preg_match_all($regexp, $mailing, $matches);
print_r($matches);
/*
resultaat:
Array
(
    [0] => Array
        (
            [0] => #aanhef#
            [1] => #user.lastname#
            [2] => #product[0]#
            [3] => #product[1]#
            [4] => #product[2]#
            [5] => #product[]#
            [6] => #prijs#
            [7] => #user.notavailable#
            [8] => #unused#
        )

    [1] => Array
        (
            [0] => aanhef
            [1] => user
            [2] => product
            [3] => product
            [4] => product
            [5] => product
            [6] => prijs
            [7] => user
            [8] => unused
        )

    [2] => Array
        (
            [0] => 
            [1] => .lastname
            [2] => [0]
            [3] => [1]
            [4] => [2]
            [5] => []
            [6] => 
            [7] => .notavailable
            [8] => 
        )

    [3] => Array
        (
            [0] => 
            [1] => lastname
            [2] => 
            [3] => 
            [4] => 
            [5] => 
            [6] => 
            [7] => notavailable
            [8] => 
        )

    [4] => Array
        (
            [0] => 
            [1] => 
            [2] => 0
            [3] => 1
            [4] => 2
            [5] => 
            [6] => 
            [7] => 
            [8] => 
        )

)
*/

